package com.moduleSys.config;

import lombok.Data;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.Resource;

/**
 * @author czw
 */
@Configuration
public class RedisConfig {

    @Resource
    public Environment env;

    @Bean
    public JedisPool redisPoolFactory() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(NumberUtils.toInt(env.getProperty("spring.redis.pool.maxIdle")));
        jedisPoolConfig.setMaxWaitMillis(NumberUtils.toLong(env.getProperty("spring.redis.pool.max-wait")));
        jedisPoolConfig.setTestOnBorrow(BooleanUtils.toBoolean(env.getProperty("spring.redis.testOnBorrow")));
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, env.getProperty("spring.redis.host"), NumberUtils.toInt(env.getProperty("spring.redis.port")),  NumberUtils.toInt(env.getProperty("spring.redis.timeout")));
        return jedisPool;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory(){
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName(env.getProperty("spring.redis.host"));
        jedisConnectionFactory.setPort(NumberUtils.toInt(env.getProperty("spring.redis.port")));
        jedisConnectionFactory.setPassword(env.getProperty("sspring.redis.password"));
        return jedisConnectionFactory;
    }
    @Bean
    public StringRedisTemplate stringRedisTemplate() {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(jedisConnectionFactory());
        return stringRedisTemplate;
    }
}
